<template>
    <!-- 纪检人员管理 -->
    <base-breadcrumb class="personManage-container">
        <searchData :searchData="searchArr" @search="handleSearch" @change="change"></searchData>
        <a-card :bordered="false">
            <div class="pub-table-action-btn mb12">
                <a-button v-btnPermission="'di_001_add_01'" type="primary" @click="handleUpdate({}, 'add')"
                    >新增</a-button
                >
                <export-mould
                    v-btnPermission="'di_001_imp_05'"
                    class="ml12"
                    buttonText="导入模板下载"
                    templateCode="纪检人员导入模板.xlsx"
                    icon="cloud-download"
                ></export-mould>
                <ExcelImportButton
                    v-btnPermission="'di_001_imp_05'"
                    class="ml12"
                    :loading="loadingState.isImport"
                    @handleSubmit="handleImport"
                ></ExcelImportButton>
                <excel v-btnPermission="'di_001_exp_06'" ref="exportBtn" fileName="纪检人员" is-click-generate="false">
                    <a-button
                        class="ml12"
                        slot="excelBtn"
                        type="primary"
                        :loading="loadingState.isExport"
                        @click="handleExport"
                        >导出</a-button
                    >
                </excel>
            </div>
            <list-table
                ref="table"
                rowKey="id"
                :columns="columns"
                :request="loadData"
                show-size-changer
                show-quick-jumper
                showPagination="auto"
            >
                <template slot="action" slot-scope="text, record">
                    <MoreButton class="pub-table-list-action">
                        <a v-btnPermission="'di_001_loo_04'" @click="handleUpdate(record, 'look')">查看</a>
                        <a v-btnPermission="'di_001_edi_02'" @click="handleUpdate(record, 'edit')">编辑</a>
                        <a
                            v-btnPermission="'di_001_del_03'"
                            v-if="record.levelName === '项目'"
                            style="cursor: not-allowed; color: #cccccc !important"
                            >删除</a
                        >
                        <a v-btnPermission="'di_001_del_03'" v-else @click="handleUpdate(record, 'delete')"
                            >删除</a
                        >
                    </MoreButton>
                </template>
            </list-table>
        </a-card>
        <!-- 导出结果 -->
        <ExportResult :visible.sync="visibleExport" :exportList="exportList" width="80%" />
    </base-breadcrumb>
</template>

<script>
import { STable } from '@/components' // 表格
import { packageConfirm } from '@/utils/baseAction.js'
import {
    getPersonList,
    deletePerson,
    importPerson,
    exportPerson
} from '@/api/disciplineInspection/orgStructure/index.js'
import Selector from '@/components/Select/Selector'
import ExportMould from '@/components/ExportMould' // 导出模板文件按钮
import ExportResult from '@/components/Dialog/ExportResult' // 弹窗
import SelectUnit from '@/components/Select/SelectUnit'
import SelectProject from '@/components/Select/SelectProject' // 项目
const searchArr = [
    {
        name: '姓名',
        value: 'name',
        type: 'input'
    },

    {
        name: '公司/分公司',
        valueKey: 'branchOrgId',
        type: SelectUnit,
        mode: 'default',
        useAll: true,
        linkage: true
    },
    // {
    //     name: '所属项目',
    //     keyValue: 'branchOrgId',
    //     valueKey: 'projectId',
    //     type: SelectProject,
    //     empty: true,
    //     emptyId: '53085e2c9f1f4685801ef31994f57c49'
    // },
    {
        name: '入职纪检时间',
        value: 'time',
        type: 'dateRange',
        attr: {
            rangeFormat: ['checkStartTime', 'checkEndTime']
        }
    }
]

const columns = [
    {
        title: '序号',
        width: 80,
        dataIndex: 'index',
        customRender() {
            return arguments[2] + 1
        }
    },
    {
        title: '姓名',
        dataIndex: 'name'
    },
    {
        title: '手机号',
        dataIndex: 'phone'
    },
    // {
    //   title: '所属层级',
    //   dataIndex: 'levelName'
    // },
    // {
    //   title: '单位',
    //   dataIndex: 'branchOrgName'
    // },
    {
        title: '公司/分公司',
        dataIndex: 'branchOrgName'
    },
    {
        title: '项目',
        dataIndex: 'projectName'
    },

    {
        title: '岗位',
        dataIndex: 'postName',
        customRender(text, record) {
            let str = record.postName,
                index = str.lastIndexOf('/')
            str = str.substring(index + 1, str.length)
            return str
            // return record.startTermOfValidity + '~' + record.endTermOfValidity
        },
        ellipsis: true
    },
    {
        title: '职称',
        dataIndex: 'jobTitle'
    },
    {
        title: '入职纪检时间',
        dataIndex: 'checkTime'
    },
    {
        title: '操作',
        dataIndex: 'action',
        width: '180px',
        align: 'center',
        scopedSlots: { customRender: 'action' }
    }
]

export default {
    name: 'a' + Date.now(),
    components: {
        STable,
        ExportMould,
        ExportResult
    },
    data() {
        return {
            loadingState: {
                isImport: false,
                isExport: false
            },
            searchArr: searchArr,
            columns: columns,
            queryParam: {},
            visibleExport: false, // 导入结果弹窗控件
            exportList: [{ columns: [], datas: [] }] // 导入配置项
        }
    },
    methods: {
        change(e) {
            console.log(e)
        },
        /**
         * 导出
         */
        async handleExport() {
            try {
                if (this.loadingState.isExport) return
                this.loadingState.isExport = true
                const res = await exportPerson(this.queryParam)
                this.loadingState.isExport = false
                const sexMap = {
                    0: '女',
                    1: '男'
                }
                const list = (res.data || []).map((item) => {
                    item.sex = sexMap[item.sex] || ''
                    return item
                })
                const columns = [
                    { title: '所属层级', dataIndex: 'levelName' },
                    { title: '单位', dataIndex: 'branchOrgName' },
                    { title: '姓名', dataIndex: 'name' },
                    { title: '手机号', dataIndex: 'phone' },
                    { title: '身份证号码', dataIndex: 'idCard' },
                    { title: '性别', dataIndex: 'sex' },
                    { title: '最高学历', dataIndex: 'specialitieMax' },
                    { title: '所学专业', dataIndex: 'specialitie' },
                    { title: '职称', dataIndex: 'jobTitle' },
                    { title: '岗位职务', dataIndex: 'postName' },
                    { title: '入职纪检时间', dataIndex: 'checkTime' },
                    { title: '主要工作经验', dataIndex: 'content' }
                ]
                this.$refs.exportBtn.generateExcel(list, { columns })
            } catch (e) {
                console.error(e)
                this.loadingState.isExport = false
            }
        },
        /**
         * 导入
         */
        async handleImport(list) {
            try {
                if (this.loadingState.isImport) return

                const columns = [
                    {
                        title: '所属层级',
                        dataIndex: 'levelName'
                    },
                    {
                        title: '单位',
                        dataIndex: 'branchOrgName'
                    },
                    {
                        title: '姓名',
                        dataIndex: 'name'
                    },
                    {
                        title: '手机号',
                        dataIndex: 'phone'
                    },
                    {
                        title: '入职纪检时间',
                        dataIndex: 'checkTime'
                    },
                    {
                        title: '主要工作经验',
                        dataIndex: 'content'
                    }
                ]
                const paramsList = []
                for (let item of list) {
                    const resultItem = {}
                    for (const key in item) {
                        const target = columns.find((column) => column.title === key)
                        if (target?.title === '入职纪检时间' && !(item[key] instanceof Date)) {
                            this.$message.warning('请输入正确的时间格式')
                            return
                        }
                        if (target) {
                            // resultItem[target.dataIndex] = target.title === '入职纪检时间' ? formatDate(item[key], '-') : item[key]
                            resultItem[target.dataIndex] = item[key]
                        }
                    }
                    paramsList.push(resultItem)
                }
                if (!paramsList.length) {
                    this.$message.warning('请录入导入数据')
                    return
                }
                this.loadingState.isImport = true
                const importRes = await importPerson(paramsList).catch(() => {
                    this.loadingState.isImport = false
                })
                this.loadingState.isImport = false
                if (importRes.code === 200) {
                    if (importRes.data?.list?.length > 0) {
                        // 表头添加失败原因
                        const columnsExport = [
                            {
                                title: '所属层级',
                                dataIndex: 'levelName'
                            },
                            {
                                title: '单位',
                                dataIndex: 'branchOrgName'
                            },
                            {
                                title: '姓名',
                                dataIndex: 'name'
                            },
                            {
                                title: '手机号',
                                dataIndex: 'phone'
                            },
                            {
                                title: '入职纪检时间',
                                dataIndex: 'checkTime'
                            },
                            {
                                title: '主要工作经验',
                                dataIndex: 'content'
                            },
                            {
                                dataIndex: 'msg',
                                ellipsis: true,
                                title: '失败原因'
                            }
                        ]

                        this.exportList = [
                            {
                                successCount: importRes.data.successCount,
                                columns: columnsExport,
                                datas: importRes.data.list
                            }
                        ]
                        this.visibleExport = true
                    } else {
                        this.$message.success('导入成功')
                    }
                    // 如果有导入成功条数，则刷新表格
                    importRes.data?.successCount > 0 && this.refreshTable()
                }
            } catch (e) {
                console.error(e)
                this.loadingState.isImport = false
            }
        },
        async loadData(parameter) {
            const requestParameters = Object.assign({}, { ...parameter }, { query: this.queryParam })
            return getPersonList(requestParameters)
        },
        handleSearch(val = {}) {
            this.queryParam = {
                ...val
            }
            this.refreshTable()
        },
        refreshTable() {
            this.$refs.table.refresh(true)
        },
        /**
         * 处理数据的相关操作（增删改查）
         */
        handleUpdate(data, pageType) {
            const commonHandler = () => {
                this.$router.push({
                    path: '/discipline/orgStructure/personManage/update',
                    query: {
                        id: data.id || '',
                        pageType: pageType,
                        levelName: data.levelName || ''
                    }
                })
            }
            const actionMap = {
                add: commonHandler,
                edit: commonHandler,
                look: commonHandler,
                delete: async () => {
                    packageConfirm({
                        callback: async () => {
                            const res = await deletePerson({ id: data.id })
                            this.$message.success('删除成功')
                            this.refreshTable()
                        }
                    })
                }
            }
            actionMap[pageType] && actionMap[pageType]()
        }
    }
}
</script>

<style>
</style>